package hhh.data.rxjava;

import hhh.data.bean.HttpResult;
import hhh.data.exception.NetworkConnectionException;
import hhh.data.exception.ServerException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * Created by Administrator on 2017/6/30 0030.
 */
public class RxResultHelper {
    public static <T> ObservableTransformer<HttpResult<T>,T> handleResult(){
//        return new ObservableTransformer<HttpResult<T>, T>() {
//            @Override
//            public ObservableSource<T> apply(Observable<HttpResult<T>> upstream) {
//                return upstream.flatMap(new Function<HttpResult<T>, ObservableSource<T>>() {
//                    @Override
//                    public ObservableSource<T> apply(final HttpResult<T> tHttpResult) throws Exception {
//                        if(tHttpResult==null){
//                            return Observable.error(new NetworkConnectionException());
//                        }else if(tHttpResult.code==HttpResult.STATE_SUC){
//                            return Observable.create(new ObservableOnSubscribe<T>() {
//                                @Override
//                                public void subscribe(ObservableEmitter<T> e) throws Exception {
//                                    e.onNext(tHttpResult.data);
//                                    e.onComplete();
//                                }
//                            });
//                        }else{
//                            return Observable.error(new ServerException(tHttpResult.code,tHttpResult.message));
//                        }
//                    }
//                });
//            }
//        };
        return new ObservableTransformer<HttpResult<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<HttpResult<T>> upstream) {
                return upstream.map(new Function<HttpResult<T>, T>() {
                    @Override
                    public T apply(HttpResult<T> tHttpResult) throws Exception {
                        if(null==tHttpResult){
                            throw new NetworkConnectionException();
                        }else if(tHttpResult.code==HttpResult.STATE_SUC){
                            return tHttpResult.data;
                        }else{
                            throw new ServerException(tHttpResult.code,tHttpResult.message);
                        }
                    }
                });
            }
        };
    }
}
